package com.heima.search.interceptor;

import com.alibaba.nacos.common.utils.StringUtils;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Lijx
 * @Date 2024-07-30 13:54
 */
@Component
public class ApTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中userId
        String userId = request.getHeader("userId");

        if (StringUtils.isNotEmpty(userId)) {
            //userId不为空，存入ThreadLocal中
            ApThreadLocalUtil.setUserId(Integer.valueOf(userId));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal线程，释放内存
        ApThreadLocalUtil.remove();
    }
}
